const mongoose = require("mongoose");
const goodsModel = mongoose.model("goods");

module.exports = {
  del: async (_id) =>
    await goodsModel.deleteOne({
      _id,
    }),
  add: async (goods) =>
    await goodsModel.create({
      check: 0,
      f_count: [],
      time: new Date(),
      status: true,
      ...goods,
    }),
  get: async ({ page = 1, limit = 10, query = {} }) => {
    limit = ~~limit;
    for (let key of Object.keys(query)) {
      if (key != "check") {
        query[key] = {
          $regex: query[key],
        };
      }
    }
    const data = {};
    data.total = await goodsModel.countDocuments();
    data.maxPage = Math.ceil(data.total / limit);
    data.rows = await goodsModel
      .find(query)
      .populate("userId")
      .sort({
        _id: -1,
      })
      .skip((page - 1) * limit)
      .limit(limit)
      .exec();
    return data;
  },
  getOne: async (_id) => await goodsModel.findOne({ _id }).populate("userId"),

  getName: async (type) => await goodsModel.find(type).populate("userId"),

  changeStatus: async ({ _id, status }) =>
    await goodsModel.updateOne({ _id }, { status }),
  update: async ({ _id }, goods) => {
    return await goodsModel.updateOne({ _id }, goods);
  },

  queryGet: async ({ page = 1, limit = 10, query = {} }) => {
    limit = ~~limit;
    const data = {};
    data.total = (
      await goodsModel.find({ ...query.accurate, $or: query.vague })
    ).length;
    data.maxPage = Math.ceil(data.total / limit);
    data.rows = await goodsModel
      .find({ ...query.accurate, $or: query.vague })
      .populate("userId")
      .sort({
        _id: -1,
      })
      .skip((page - 1) * limit)
      .limit(limit)
      .exec();
    return data;
  },
  getFromUserId: async (userId) => await goodsModel.find({ userId }),
  // 发布信息页首次获取数据
  getFromUserIdNow: async (userId) => await goodsModel.find({ userId }).sort({_id:-1}).populate(`userId`),
};
